from google.appengine.api import users
from google.appengine.ext import db
import jinja2, os, webapp2, urllib, cgi, sessions, displugged, logger
from datatypes import *


jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class accountEdit(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('dynamic/userSettings.html')
        user = sessions.ourUserModel()
        safeURLName = urllib.quote(user.username)
        self.response.out.write(template.render(
            {'navbar': displugged.navbar(self),
             'user': user,
             'safeURLName': safeURLName}))

    def post(self):
        user = sessions.ourUserModel()
        firstName = self.request.get('fname')
        middleName = self.request.get('mname')
        lastName = self.request.get('lname')
        bio = self.request.get('bio')
        #sanity check
        if not (firstName and lastName):
            displugged.giveError(self, "You are missing information.")
            return
        logger.log("{0} has changed their profile.".format(user.username))

        user.put()

class accountView(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('dynamic/profile.html')
        user_url = self.request.get("user")
        if user_url:
            user = User.get_by_key_name(user_url, parent=UserPathGen())
        else:
            user = sessions.ourUserModel()
        self.response.out.write(template.render({'navbar': displugged.navbar(self),
                                                 'user': user}))

app = webapp2.WSGIApplication([('/users/myaccount', accountEdit),
                               ('/users/accounts', accountView)
                               ],
                              debug = True)
